<template>
    <div class="assign">
        <el-tree style="max-width:  100%;" ref="treeRef" node-key="id" :data="data" show-checkbox default-expand-all
            :props="defaultProps" :default-checked-keys="permIdsArr.permIds" @check-change="handleNodeClick" />
        <div style="margin: 15px 0px 0px 300px;">
            <el-button style="color: white;background-color: #2752fb;border-radius: 0px;height: 28px;"
                @click="assignPrem">确定</el-button>
            <el-button style="border-radius: 0px;height: 28px;"
                @click="store.$state.dialogVisible = false">取消</el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watchEffect, nextTick } from 'vue'
import { assignPermission } from '@/api/role'
import { useStore } from '@/stores/counter'
import { ElTree } from 'element-plus'
import { ElMessageBox, ElMessage } from "element-plus";

let store = useStore()
let y = defineProps(['permIdsArr', 'render'])
const defaultProps = {
    children: 'children',
    label: 'name',
}
//权限回显
let permIdsnewArr: any = ref([])
import { getRoleList } from "@/api/jurisdiction"
const data = ref([])
const render2 = () => {
    getRoleList().then(res => {
        getDD(res.data.data)
        data.value = getDD(res.data.data)
    })
}
//分配权限
const handleNodeClick = (data: any, e: Boolean) => {
    permIdsnewArr.value = y.permIdsArr.permIds
    if (e) {
        permIdsnewArr.value.push(data.id)
        console.log(permIdsnewArr.value);
    } else {
        permIdsnewArr.value.splice(permIdsnewArr.value.indexOf(data.id), 1)
        console.log(permIdsnewArr.value);
    }
}
//分配权限-角色
const assignPrem = () => {
    assignPermission({ id: y.permIdsArr.id, permIds: permIdsnewArr.value }).then((res: any) => {
        if (res.data.code == 10000) {
            ElMessage({
                message: res.data.message,
                type: 'success'
            })
            store.$state.dialogVisible = false
            y.render()
            return
        }
        ElMessage({
            message: res.data.message,
            type: 'warning'
        })
        return
    })
}
const getDD = (data: any, id = 0) => {
    let arr1: any = [];
    let arr2: any = [];
    data.forEach((item: any) => {
        if (item.pid == id) {
            arr2 = getDD(data, item.id);
            if (arr2.length > 0) {
                item.children = arr2;
            }
            arr1.push(item);
        }
    });
    return arr1;
}
onMounted(() => {
    render2()
})

</script>

<style>
.assign {
    .el-tree-node__label {
        font-size: 14px;
    }

    .el-tree-node__content {
        height: 40px;
    }
}
</style>